const mongoose = require('mongoose');
const Cate = require('../models/cate.model');

exports.create = function(req, res, next) {
  const cate = new Cate(req.body);
  cate.save().then(data => {
    res.json(data);
  });
};

exports.update = function(req, res, next) {
  var id = req.params.id;
  Cate.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
    res.json(data);
  });
};

function reverseTree(data, pid) {
  var result = [],
    temp;

  var data = JSON.parse(JSON.stringify(data)); // 将mongoose的数据模型的对象转成字符串，再将字符串转成 JS Object

  for (var i in data) {
    if (data[i].parentId === pid) {
      result.push(data[i]); // 暂时只有一个对象
      temp = reverseTree(data, data[i]._id); // data[i]._id === 1
      if (temp.length > 0) {
        data[i].children = temp;
      }
    }
  }

  return result;
}

exports.list = function(req, res, next) {
  var type = req.params.type || 1;

  console.log(type);
  Cate.find({ type: type }, function(err, data) {
    var rpTree = reverseTree(data, null);
    res.json(rpTree);
  });
};

exports.remove = function(req, res, next) {
  var id = req.params.id;
  var ids = [];
  Cate.findOne({ _id: id }, function(err, doc) {
    if (doc) {
      ids = [doc._id]; //

      doc.getChildren().then(function(docs) {
        for (var i = 0; i < docs.length; i++) {
          ids.push(docs[i]._id);
        }


        Cate.remove({ _id: { $in: ids } }).then(data => {
          res.json({ message: '删除多条记录成功', status: 200 });
        });
      });
    }
  });

  //
};
